package com.smart.sso.server.controller.admin;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.mvc.model.Pagination;
import com.smart.mvc.model.Result;
import com.smart.mvc.validator.Validator;
import com.smart.mvc.validator.annotation.ValidateParam;
import com.smart.sso.server.controller.common.BaseController;
import com.smart.sso.server.log.SystemControllerLog;
import com.smart.sso.server.model.NodeDB;
import com.smart.sso.server.service.NodeDBService;
import com.smart.sso.server.switchdb.DBContextHolder;
import com.smart.sso.server.util.OperationUtils;

import ch.qos.logback.core.pattern.parser.Node;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "节点管理")
@Controller
@RequestMapping("/admin/nodeDB")
public class NodeDBController extends BaseController{

	@Resource
	private NodeDBService nodeDBService;
	
	@ApiOperation("初始页")
	@RequestMapping(method = RequestMethod.GET)
	public String execute() {
		return "/admin/nodeDB";
	}
	
	@ApiOperation("节点列表")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody Result list(
			@ApiParam(value = "开始页码", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer pageNo,
			@ApiParam(value = "显示条数", required = true) @ValidateParam({ Validator.NOT_BLANK }) Integer pageSize,
			HttpServletRequest request) {
		Pagination<NodeDB> pagination = new Pagination<>(pageNo, pageSize);
		nodeDBService.findByAllPagination(pagination);
		return Result.createSuccessResult().setData(pagination);
	}
	
	@ApiOperation("新增/修改页")
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(@ApiParam(value = "id") Integer id, Model model) {
		NodeDB nodeDB;
		if (id == null) {
			nodeDB = new NodeDB();
		}
		else {
			nodeDB = nodeDBService.get(id);
		}
		model.addAttribute("nodeDB", nodeDB);
		return "/admin/nodeDBEdit";
	}
	
	@ApiOperation("新增/修改提交")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_node_add ,description = "新增节点")
	public @ResponseBody Result save(
			HttpServletRequest request,
			@ApiParam(value = "id") Integer id,
			@ApiParam(value = "名称", required = true) @ValidateParam({ Validator.NOT_BLANK }) String name,
			@ApiParam(value = "ip地址", required = true) @ValidateParam({ Validator.NOT_BLANK }) String ip,
			@ApiParam(value = "管理员名称", required = true) @ValidateParam({ Validator.NOT_BLANK }) String adminName,
			@ApiParam(value = "密码" , required =true) @ValidateParam({Validator.NOT_BLANK}) String password,
			@ApiParam(value = "节点数据库名称" , required = true) @ValidateParam({Validator.NOT_BLANK}) String dbName) {
		NodeDB nodeDB;
		if (id == null) {
			nodeDB = new NodeDB();
		}
		else {
			nodeDB = nodeDBService.get(id);
		}
		nodeDB.setName(name);
		nodeDB.setIp(ip);
		nodeDB.setAdminName(adminName);
		nodeDB.setPassword(password);
		nodeDB.setDbName(dbName);
		if(id == null) {
			List<NodeDB> exist = nodeDBService.findByDBname(dbName);
			if (!exist.isEmpty()) {
				return Result.create(0).setMessage("该数据库已存在，请重新命名");
			}
		}
		nodeDBService.save(nodeDB);
//		nodeDBService.update(nodeDB);
		return Result.createSuccessResult();
	}
	
	@ApiOperation("删除节点/提交")
	@RequestMapping(value = "/delete/submit" , method = RequestMethod.POST)
	@SystemControllerLog(operationId = OperationUtils.operation_node_delete ,description = "删除节点")
	public @ResponseBody Result deleteMemberSubmit(
			@ApiParam(value="ids" , required = true) @ValidateParam({Validator.NOT_BLANK}) String ids) {
		List<Integer> idList = getAjaxIds(ids);
		for(int i=0 ; i< idList.size() ; i++) {
			NodeDB nodeDB = nodeDBService.get( idList.get(i) );
			nodeDBService.delete(nodeDB);
		}
		return Result.createSuccessResult().setMessage("删除节点成功！");
	}
	
	@ApiOperation("切换节点")
	@RequestMapping(value = "/change" , method =RequestMethod.GET)
	@SystemControllerLog(operationId = OperationUtils.operation_node_change ,description = "切换节点")
	public String changDatabase(@ApiParam(value = "id") Integer id , HttpServletRequest request ,
			HttpServletResponse response) throws Exception {
		NodeDB nodeDB = nodeDBService.get(id);
		NodeDB currentDB = (NodeDB) request.getSession().getAttribute("CURRENT_NODE");
		if(nodeDB == null && currentDB !=null)
			nodeDB = currentDB;
		String nodeKey = "NODE_" + id;
		request.getSession().setAttribute("NODE_KEY", nodeKey);
		request.getSession().setAttribute("CURRENT_NODE", nodeDB);
		request.getSession().setAttribute("NODE_NAME", nodeDB.getName());
//		return "redirect:/admin/admin";
		return "redirect:/admin/nodeDB";
//		response.sendRedirect("/smart-sso-server/admin/admin#/admin/nodeDB");
	}
	
	@ApiOperation("返回默认节点")
	@RequestMapping(value = "/default" , method =RequestMethod.GET)
	@SystemControllerLog(operationId = OperationUtils.operation_node_reset ,description = "返回主节点")
	public String changDatabase(HttpServletRequest request) {
		request.getSession().setAttribute("NODE_KEY", "MASTER");
		return "redirect:/admin/nodeDB";
	}
	
	@ApiOperation("同步数据库")
	@RequestMapping(value = "/synchronize" , method = RequestMethod.GET)
	@SystemControllerLog(operationId = OperationUtils.operation_synchronize_database ,description = "同步数据库")
	public @ResponseBody Result synchronizeDB() {
		try {
			nodeDBService.synchronizeDB();
		}catch (Exception e) {
			// TODO: handle exception
			return Result.createSuccessResult().setMessage("有节点连接失败");
		}
		return Result.createSuccessResult().setMessage("同步成功");
	}
}
